﻿// make_shared_Test.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <vector>
#include <map>

using namespace std;

#if 0
class StructA
{
public:
    int i;
    string str;
    StructA(int i) {
        this->i = i;
        cout << "StructA(int),line = " << __LINE__ << endl;
    };
    StructA(string str) {
        this->str = str;
        cout << "StructA(string), line = " << __LINE__ << endl;
    }
    ~StructA() { cout << "~StructA " << endl; };

    void show() {
        cout << "show() is Called. line = " << __LINE__ <<endl;
    }
protected:
private:
};

int main()
{
    //make_shared 自动申请对象及内存，自动释放，不用手动执行new和delete
    shared_ptr<StructA> pA = make_shared<StructA>(123);
    cout << "pA->i = " << pA->i << endl;

    shared_ptr<StructA> pB = make_shared<StructA>("hello");
    cout << "pB->str = " << pB->str << endl;
    pB->show();

    auto t = make_shared<StructA>("Number One!");
    cout << "t->str = " << t->str << endl;
    t->show();

    return 0;
}
#endif

class StructA
{
public:
    int i;
    StructA(int i) {
        this->i = i;
        cout << "StructA(int), line = " << __LINE__ << endl;
    };
    ~StructA() { cout << "~StructA" << endl; };

    void show() {
        cout << "show() is called. line = " << __LINE__ << endl;
    };

#if 1
    template <class T>
    T add(const T& x) {
        return x;
    }
#endif
private:

};

int main()
{
    map<int, shared_ptr<StructA>> mStrA;
    //插入map映射key-value数据
    mStrA[0] = make_shared<StructA>(123);
    mStrA[1] = make_shared<StructA>(456);
    mStrA.insert(pair<int, shared_ptr<StructA>>(2, make_shared<StructA>(789)));
    mStrA.insert(pair<int, shared_ptr<StructA>>(3, make_shared<StructA>(333)));

    mStrA[0]->show();
    //遍历方式1
    for (auto &mA : mStrA)
    {
        cout << mA.first << ":" << mA.second->i << endl;
    }
    cout << endl;

    //遍历方式2
    map<int, shared_ptr<StructA>>::iterator iter;
    for (iter = mStrA.begin(); iter != mStrA.end(); iter++)
    {
 //       cout << iter->first << ":" << iter->second->i << endl;
        cout << iter->second->add(iter->first) <<endl;
        cout << iter->second->add<const char*>("char") << endl;;
        cout << iter->second->add<string>("string") << endl;;
    }
    return 0;
}